<template>
  <el-dialog :title="dynamicTitle" :visible.sync="dialogForm.visible" @closed="handleClose('ruleForm')" width="600px">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">

      <el-form-item label="问卷学院" prop="collegeId">
        <el-select
          v-model="ruleForm.collegeId"
          @change="changeCollege"
          :disabled="isEdit"
          placeholder="请选择学院">
          <el-option
            v-for="(item, inx) in collegeList"
            :key="inx"
            :label="item.dictLabel"
            :value="item.dictValue">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item v-if="!isEdit" label="问卷对应课程" prop="courseId">
        <el-select
          v-model="ruleForm.courseId"
          :loading="courseLoading"
          @change="changeCourse"
          placeholder="请选择课程">
          <el-option
            v-for="(item, inx) in courseList"
            :key="inx"
            :label="item.title"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item v-if="!isEdit" label="问卷对应期" prop="courseChannelId">
        <el-select
          v-model="ruleForm.courseChannelId"
          :loading="stageLoading"
          placeholder="请选择期次">
          <el-option
            v-for="(item, inx) in stageList"
            :key="inx"
            :label="item.title"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item v-if="isEdit" label="问卷名称" prop="questionName">
        <el-input v-model="ruleForm.questionName" disabled style="width: 205px;"></el-input>
      </el-form-item>

      <el-form-item label="问卷对象" prop="questionScope">
        <el-radio-group v-model="ruleForm.questionScope" size="medium">
          <el-radio border label="ALL">全部学员</el-radio>
          <el-radio border label="FORMAL">正式课学员</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="关联模板" required>
        <el-col :span="11">
          <el-form-item prop="templateId">
            <el-select v-model="ruleForm.templateId" placeholder="请选择调查问卷模板">
              <el-option
                v-for="(item, inx) in quesTemplates"
                :key="inx"
                :label="item.templateName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8" :offset="1">
          <el-button type="primary" @click="handlePreview">预览</el-button>
        </el-col>
      </el-form-item>

      <el-form-item label="问卷周期" required>
        <el-col :span="11">
          <el-form-item prop="startTime">
            <el-date-picker
              type="datetime"
              v-model="ruleForm.startTime"
              placeholder="开始日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
        
        <el-col class="date-line" :span="2">-</el-col>

        <el-col :span="11">
          <el-form-item prop="endTime">
            <el-date-picker
              type="datetime"
              v-model="ruleForm.endTime"
              placeholder="结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item label="备注" prop="remarks">
        <el-input
          type="textarea"
          v-model="ruleForm.remarks"
          :rows="3"
          maxlength="100"
          show-word-limit
          placeholder="不能超过100字">
        </el-input>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="success" @click="handleSubmit('ruleForm')" :disabled="this.type === 'preview'">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { sysNormalDisable } from '@utils/dictionariesFunc'

import {
  courseList,
  stageList,
  templates,
  addQuestionnaires,
  questionnairesDetails,
  editQuestionnaires
} from '@/api/survey'

const templateDic = {
  1: { key: 'shengxue' },
  2: { key: 'zhuanxianger' },
  3: { key: 'zhuanxiangyi' },
  4: { key: 'rumen' }
}

export default {
  props: {
    dialogForm:{
      type: Object,
      default: function () {}
    }
  },
  
  data() {
    return {
      // Select Obj
      collegeList: [],
      courseList: [],
      stageList: [],
      quesTemplates: [],

      // 下拉框加载···
      courseLoading: false,
      stageLoading: false,
      
      // Model
      ruleForm: {
        courseId:'',//课程id
        courseChannelId:'',//期刊id
        collegeId: '',
        startTime: '',
        endTime: '',
        questionScope: '',
        questionName: '',
        templateId: '',
        remarks: ''
      },

      // validate
      rules: {
        collegeId: [
          { required: true, message: '请选择学院', trigger: 'change' }
        ],
        courseId: [
          { required: true, message: '请选择课程', trigger: 'change' }
        ],
        courseChannelId: [
          { required: true, message: '请选择对应期', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        questionScope: [
          { required: true, message: '请选择问卷对象', trigger: 'change' }
        ],
        templateId: [
          { required: true, message: '请选择调查问卷模板', trigger: 'change' }
        ],
        questionName: [
          { required: true, message: '请输入问卷名称', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    // 返回表单类型
    type: function () {
      return this.dialogForm.type
    },

    // 编辑/查看
    isEdit: function() {
      return this.type === 'preview' || this.type === 'edit'
    },

    // 动态标题
    dynamicTitle: function() {
      if( this.type === 'edit') {
        return '编辑问卷'
      }

      if( this.type === 'preview') {
        return '查看问卷' 
      }

      if (this.type === 'add') {
        return '新增问卷'
      }
    }
  },

  watch: {
    // 当打开类型为编辑或查看，查询问卷详情
    'dialogForm.visible':function (newVal, oldVal) {
      if(this.dialogForm.visible && (this.type === 'preview' || this.type === 'edit')) {
        this.handleFillForm()
      }
    }
  },

  async mounted() {
    // 查询学院字典
    let college = await sysNormalDisable('sys_college', 'collegeType')
    this.collegeList = this.collegeList.concat(college)

    // 查询问卷模板列表
    templates({ templateStatus: 'OPEN' }, (res) => {
      this.quesTemplates = res.rows
    })
  },

  methods: {
    /** 切换学院 */
    changeCollege() {
       
      this.ruleForm.courseId = ''
      this.ruleForm.courseChannelId = ''
      this.courseList = []
      this.stageList = []
      this.courseLoading = true

      const params = {
        collegeId: this.ruleForm.collegeId
      }
      
      courseList(params, (res) => {
        this.courseList = res
        this.courseLoading = false
      },(err) => {
        this.$message({
          message: err.message,
          type: 'warning'
        })
      })
    },

    /** 切换课程 */
    changeCourse() {
       
      this.ruleForm.courseChannelId = ''
      this.stageList = []
      this.stageLoading = true
      
      stageList(this.ruleForm.courseId, (res) => {
        this.stageList = res
        this.stageLoading = false
      },(err) => {
        this.$message({
          message: err.message,
          type: 'warning'
        })
      })
    },

    /** 重置输入内容 */
    handleClose(formName) {
      this.$refs[formName].resetFields()
      // 同时清空下拉列表数据
      this.courseList = []
      this.stageList = []
    },

    /** 预览模板 */
    handlePreview() {
      if(!this.ruleForm.templateId) {
        this.$message.info('请选择一个调查问卷模板')
        return
      }
      
      const template = templateDic[this.ruleForm.templateId].key
      const params = `/survey/?type=${template}&preview=true`
      window.open(process.env.VUE_APP_WAP_URL + params, '_blank')
    },

    /** 时间周期的校验 */
    handleDate() {
      const { endTime, startTime } = this.ruleForm
      const end = Date.parse(new Date(endTime))
      const start = Date.parse(new Date(startTime))
      return end < start ? true : false
    },

    /** 填充form表单 */
    handleFillForm() {
      questionnairesDetails(this.dialogForm.questionId, (res) => {
        this.ruleForm.courseId = ''
        this.ruleForm.courseChannelId = ''
        this.ruleForm.collegeId = res.collegeId
        this.ruleForm.startTime = res.startTime
        this.ruleForm.endTime = res.endTime
        this.ruleForm.questionScope = res.questionScope
        this.ruleForm.questionName = res.questionName
        this.ruleForm.templateId = res.templateId
        this.ruleForm.remarks = res.remarks
      },(err) => {
        this.$message({
          message: err.message,
          type: 'warning'
        })
      })
    },

    handleSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {

          // 检验时间周期
          if(this.handleDate()) {
            this.$message.warning('请设置正确的时间周期')
            return false
          }

          // 处理问卷名称
          if(this.type === 'add') {
            const { courseId, courseChannelId } = this.ruleForm
            const courseObj = this.courseList.find(item => { return item.id === courseId })
            const stageObj = this.stageList.find(item => { return item.id === courseChannelId })
            this.ruleForm.questionName = courseObj.title + '-' + stageObj.title

            addQuestionnaires(this.ruleForm, (res) => {
              this.$emit('onSubmit')
            },(err) => {
              this.$message({
                message: err.message,
                type: 'warning'
              })
            })

          } else {
            
            const id = this.dialogForm.questionId
            editQuestionnaires(id ,this.ruleForm, (res) => {
              this.$emit('onSubmit')
            },(err) => {
              this.$message({
                message: err.message,
                type: 'warning'
              })
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.date-line {
  text-align: center;
}
</style>